package com.primaryedu.ui.app.growstep;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.primaryedu.R;
import com.primaryedu.bean.DynamicphotoBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.PhotosDialog;
import com.primaryedu.photo.PhotoPickerActivity;
import com.primaryedu.photo.PhotoPickerIntent;
import com.primaryedu.photo.PhotoPreviewActivity;
import com.primaryedu.photo.PhotoPreviewIntent;
import com.primaryedu.photo.SelectModel;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.CameraActivity;
import com.primaryedu.utils.ImageUtil;
import com.primaryedu.utils.UploadUtil;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.MyGridView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.microedition.khronos.opengles.GL;

import okhttp3.Call;
import okhttp3.internal.Util;

/**
 * 发布动态
 *
 * @author jun.wang
 * @description
 * @data 2018年1月9日
 */
public class DynamicPublishActivity extends BaseActivity implements OnClickListener, UploadUtil.OnUploadProcessListener {
    private String TAG = com.primaryedu.ui.app.growstep.DynamicPublishActivity.class.getSimpleName();
    MyGridView gridView;
    private GridAdapter gridAdapter;
    private TextView text_grade;
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2; //
    protected static final int UPLOAD_VIDEO_DONE = 6; //
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;

    private PhotosDialog.Builder builder;
    Dialog dialog;
    LayoutInflater inflater;
    private String picpath1 = "";
    private String picpath2 = "";
    private String picpath3 = "";
    private String picpath4 = "";
    private String picpath5 = "";
    private String picpath6 = "";
    private String picpath7 = "";
    private String picpath8 = "";
    private String picpath9 = "";
    boolean ispreview = true;
    private static final int REQUEST_PHOTO = 1;// 拍照
    private static final int REQUEST_CAMERA_CODE = 10;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private final static int CLASSANDGRADE = 30; // "申请"返回的结果码
    private ArrayList<String> imagePaths = new ArrayList<>();
    private ImageView videoCover;
    private String video = "";
    private FrameLayout Video_play_quan;
    private ArrayList<String> list = new ArrayList<>();
    private EditText et_content_publish;
    private LinearLayout ll_class_grade;
    private String classid;
    private String className;
    private String video_path = "";
    List<DynamicphotoBean> list_dynamicphoto = new ArrayList<>();
    private String picpath_vedio = "";
    private String dynamic_picpath;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case UPLOAD_FILE_DONE:
                    dismissLoading();
                    String jsonStr = msg.obj.toString();
                    System.out.println("json===" + jsonStr);

                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");

                        if (result == 1) {
                            String data = json.getString("data");
                            JSONObject listObj = new JSONObject(data);
                            String webServerUrl = listObj.getString("webServerUrl");
                            dynamic_picpath = listObj.getString("picpath1");
                            Log.i("yy", "handleMessage: picpath1========" + dynamic_picpath);
                            Log.i("yy", "handleMessage: webServerUrl========" + webServerUrl + dynamic_picpath);

                            if (imagePaths.contains(webServerUrl + dynamic_picpath)) {
                                imagePaths.remove(webServerUrl + dynamic_picpath);
                            }
                            imagePaths.add(webServerUrl + dynamic_picpath);
                            if (imagePaths.contains("paizhao")) {
                                imagePaths.remove("paizhao");
                                imagePaths.add("paizhao");
                            } else {
                                imagePaths.add("paizhao");
                            }
                            Log.i(TAG, "handleMessage: imagePahts======" + imagePaths.toString());
                            if (!TextUtils.isEmpty(dynamic_picpath)) {
                                DynamicphotoBean bean = new DynamicphotoBean();
                                bean.setIcon(dynamic_picpath);
                                list_dynamicphoto.add(bean);
                            }
                            if (null != imagePaths && imagePaths.size() != 0) {
                                gridAdapter = new GridAdapter(imagePaths);
                                gridView.setAdapter(gridAdapter);
                            }


                        } else {
                            showToast(reason);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case UPLOAD_VIDEO_DONE:
                    dismissLoading();
                    String jsonString = msg.obj.toString();
                    System.out.println("json===" + jsonString);

                    try {
                        JSONObject json = new JSONObject(jsonString);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");

                        if (result == 1) {
                            String data = json.getString("data");
                            Log.i("yy", "handleMessage: data" + data);
                            JSONObject listObj = new JSONObject(data);
                            picpath_vedio = listObj.getString("picpath1");
                            String webServerUrl = listObj.getString("webServerUrl");
                            video_path = webServerUrl + picpath_vedio;
//							JSONArray listarray = new JSONArray(data);
//							String pic = listarray.getString(0);
                            Log.i("yy", "handleMessage: video_path========" + video_path);
//							String webServerUrl = listObj.getString("webServerUrl") ;
//							mVideo.setVideoPath(video_path);
//							mVideo.start();
//							if(!TextUtils.isEmpty(video_path)){
//								Releasethedynamic();
//							}

                            MediaMetadataRetriever media = new MediaMetadataRetriever();

                            media.setDataSource(video_path, new HashMap<String, String>());
                            Bitmap frameAtTime = media.getFrameAtTime();
                            videoCover.setImageBitmap(frameAtTime);


                        } else {
                            showToast(reason);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }

        ;
    };
    private Uri photoUri;
    private String picPath = "";
    //在VideoActivity中销毁此Acitity
    static Activity DynamicPublishActivity;
    private ImageView iv_video_play;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_dynamic_publish);
        DynamicPublishActivity = this;
//        init();
    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("发布动态");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setText("发布");
        ((TextView) findViewById(R.id.text_right)).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setTextColor(getResources().getColor(R.color.main_button));

        et_content_publish = (EditText) findViewById(R.id.et_content_publish);
//		ll_class_grade = (LinearLayout)findViewById(R.id.ll_class_grade);
//		ll_class_grade.setOnClickListener(this);

        inflater = LayoutInflater.from(this);
        videoCover = (ImageView) findViewById(R.id.video_cover);
        iv_video_play = (ImageView) findViewById(R.id.iv_video_play);
        Video_play_quan = (FrameLayout) findViewById(R.id.Video_play_quan);
        Video_play_quan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				playVideo(video);
//				mVideo.start();
            }
        });
        gridView = (MyGridView) this.findViewById(R.id.gridView);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//		mAdapter = new GridAdapter(this);
//		mAdapter.update();
//		gridView.setAdapter(mAdapter);

        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs)) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(9); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
//					Toast.makeText(DynamicPublishActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
                    intent.setCurrentItem(position);
                    //如果不加这行会导致选完图片以后在主界面点击图片预览会多出一张没有default_error 的图片
                    imagePaths.remove(imagePaths.size() - 1);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        imagePaths.add("paizhao");
        gridAdapter = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        text_grade = (TextView) this.findViewById(R.id.text_grade);
        text_grade.setOnClickListener(this);
        Log.i(TAG, "getParams:userId== " + GlobalData.getUserId(getApplicationContext()));
//		Log.i(TAG, "getParams:getNickname== "+ GlobalData.accountBean.getData().getNickname());
//		Log.i(TAG, "getParams:userName== "+ GlobalData.accountBean.getData().getName());
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_dynamic_publish;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText("发布动态");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setText("发布");
        ((TextView) findViewById(R.id.text_right)).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setTextColor(getResources().getColor(R.color.main_button));

        et_content_publish = (EditText) findViewById(R.id.et_content_publish);
//		ll_class_grade = (LinearLayout)findViewById(R.id.ll_class_grade);
//		ll_class_grade.setOnClickListener(this);

        inflater = LayoutInflater.from(this);
        videoCover = (ImageView) findViewById(R.id.video_cover);
        iv_video_play = (ImageView) findViewById(R.id.iv_video_play);
        Video_play_quan = (FrameLayout) findViewById(R.id.Video_play_quan);
        Video_play_quan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				playVideo(video);
//				mVideo.start();
            }
        });
        gridView = (MyGridView) this.findViewById(R.id.gridView);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//		mAdapter = new GridAdapter(this);
//		mAdapter.update();
//		gridView.setAdapter(mAdapter);

        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs)) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(9); // 最多选择照片数量，默认为6
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
//					Toast.makeText(DynamicPublishActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
                    intent.setCurrentItem(position);
                    //如果不加这行会导致选完图片以后在主界面点击图片预览会多出一张没有default_error 的图片
                    imagePaths.remove(imagePaths.size() - 1);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
        imagePaths.add("paizhao");
        gridAdapter = new GridAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);
        text_grade = (TextView) this.findViewById(R.id.text_grade);
        text_grade.setOnClickListener(this);
        Log.i(TAG, "getParams:userId== " + GlobalData.getUserId(getApplicationContext()));
//		Log.i(TAG, "getParams:getNickname== "+ GlobalData.accountBean.getData().getNickname());
//		Log.i(TAG, "getParams:userName== "+ GlobalData.accountBean.getData().getName());
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

//			case R.id.ll_class_grade://所在班级
//				intent = new Intent(DynamicPublishActivity.this, GradeListActivity.class);
//				startActivityForResult(intent, CLASSANDGRADE);
//				startActivity(intent);
//				break;
            case R.id.text_right://发布动态
                if (imagePaths.contains("paizhao")) {
                    imagePaths.remove("paizhao");
                }
                if (imagePaths.size() != 0) {
                    if (imagePaths.size() == 1) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picPath = picpath1;
                    } else if (imagePaths.size() == 2) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picPath = picpath1 + "," + picpath2;
                    } else if (imagePaths.size() == 3) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3;
                    } else if (imagePaths.size() == 4) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4;
                    } else if (imagePaths.size() == 5) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picpath5 = list_dynamicphoto.get(4).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4 + "," + picpath5;
                    } else if (imagePaths.size() == 6) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picpath5 = list_dynamicphoto.get(4).getIcon();
                        picpath6 = list_dynamicphoto.get(5).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4 + "," + picpath5 + "," + picpath6;
                    } else if (imagePaths.size() == 7) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picpath5 = list_dynamicphoto.get(4).getIcon();
                        picpath6 = list_dynamicphoto.get(5).getIcon();
                        picpath7 = list_dynamicphoto.get(6).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4 + ","
                                + picpath5 + "," + picpath6 + "," + picpath7;
                    } else if (imagePaths.size() == 8) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picpath5 = list_dynamicphoto.get(4).getIcon();
                        picpath6 = list_dynamicphoto.get(5).getIcon();
                        picpath7 = list_dynamicphoto.get(6).getIcon();
                        picpath8 = list_dynamicphoto.get(7).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4 + ","
                                + picpath5 + "," + picpath6 + "," + picpath7 + "," + picpath8;
                    } else if (imagePaths.size() == 9) {
                        picpath1 = list_dynamicphoto.get(0).getIcon();
                        picpath2 = list_dynamicphoto.get(1).getIcon();
                        picpath3 = list_dynamicphoto.get(2).getIcon();
                        picpath4 = list_dynamicphoto.get(3).getIcon();
                        picpath5 = list_dynamicphoto.get(4).getIcon();
                        picpath6 = list_dynamicphoto.get(5).getIcon();
                        picpath7 = list_dynamicphoto.get(6).getIcon();
                        picpath8 = list_dynamicphoto.get(7).getIcon();
                        picpath9 = list_dynamicphoto.get(8).getIcon();
                        picPath = picpath1 + "," + picpath2 + "," + picpath3 + "," + picpath4 + ","
                                + picpath5 + "," + picpath6 + "," + picpath7 + "," + picpath8 + "," + picpath9;
                    }
                    Log.i(TAG, "picPath========= " + picPath);
                    //发布动态

                }
                if (Utils.ContainsEmoji(et_content_publish.getText().toString())){
                    showToast("请不要输入特殊字符！");
                }else {
                    Releasethedynamic();
                }

                break;
            case R.id.video_cover:
//				playVideo(video);
                intent = new Intent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this, VideoActivity.class);
                intent.putExtra("video_path", video_path);
                intent.putExtra("isclassdynamic", "0");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void uploadvideo(String video) {
        String fileKey = "video";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

//		Map<String, String> params = new HashMap<String, String>();
//		params.put("userid",GlobalData.accountBean.getId());
        String requestURL = Contants.course_api + "/rest/upload/video";
        uploadUtil.uploadFile(video, fileKey,
                requestURL, null);
    }

    private void Releasethedynamic() {
        showLoading("发布中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.releaseDynamicsave,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("getPublishListJson==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            Log.i("yy", "data=======================>" + result);
                            if (result == 1) {
                                showToast("发布成功！");
                                finish();
                            } else {
                                showToast("必布失败！");
//                                showToast("请不要输入特殊字符！");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("发布失败，请重新发布！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                map.put("userName", GlobalData.getUsername(getApplicationContext()));
                map.put("nickName", GlobalData.getUserNickname(getApplicationContext()));
                map.put("classId", GlobalData.getClassid(getApplicationContext()));
                map.put("className", GlobalData.getClassname(getApplicationContext()));
                Log.i("yy", "userName=======================>" + GlobalData.getClassname(getApplicationContext()));
                Log.i("yy", "classId=======================>" + GlobalData.getClassid(getApplicationContext()));
                Log.i("yy", "className=======================>" + GlobalData.getClassname(getApplicationContext()));
                map.put("content", et_content_publish.getText().toString());
                map.put("images", picPath);
                map.put("video", picpath_vedio);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void loadAdpater(ArrayList<String> paths, boolean ispreview) {

        if (ispreview) {
            imagePaths.clear();
            if (paths.contains("paizhao")) {
                paths.remove("paizhao");
                paths.add("paizhao");
            } else {
                paths.add("paizhao");
            }
            imagePaths.addAll(paths);
            gridAdapter = new GridAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);

//			imagePaths.addAll(paths);

            Log.i("yy", "loadAdpater: paths.size======" + paths.size());
            Log.i("yy", "loadAdpater: paths.size======" + paths.toString());
            Log.i("yy", "loadAdpater: imagePaths.size======" + imagePaths.toString());
            Log.i("yy", "loadAdpater: imagePaths.size======" + imagePaths.toString());
//			Log.i("yy", "loadAdpater: paths.get(2)===== "+ paths.get(2));
//			if (imagePaths.size() > 8) {
//				showToast("动态最多选择九张图片！");
//			} else {
//				for (int i = 0; i < paths.size(); i++) {
//					String imagepath = ImageUtil.compressImage(paths.get(i),Config.SDPATH_HEAD +"temp_photo.jpg",30);
//					toUploadFile(imagepath);
//				}
//			}
//			gridAdapter = new GridAdapter(imagePaths);
//			gridView.setAdapter(gridAdapter);
        } else {

            if (imagePaths != null && imagePaths.size() > 0) {
                imagePaths.remove("paizhao");
            }
            if (paths.contains("paizhao")) {
                paths.remove("paizhao");
            }
            Log.i(TAG, "数量: pathsize===" + paths.size());
            if (imagePaths.size() > 8) {
                showToast("动态最多选择九张图片！");
            } else {
                showLoading("加载中...");
                for (int i = 0; i < paths.size(); i++) {
                    String imagepath = ImageUtil.compressImage(paths.get(i), Config.SDPATH_HEAD + "temp_photo.jpg", 30);
                    toUploadFile(imagepath);
                }
            }
        }

//		paths.add("paizhao");
//		imagePaths.addAll(paths);
//		gridAdapter  = new GridAdapter(imagePaths);
//		gridView.setAdapter(gridAdapter);
        try {
            JSONArray obj = new JSONArray(imagePaths);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        if (video != "") {
            msg.what = UPLOAD_VIDEO_DONE;
        } else {
            msg.what = UPLOAD_FILE_DONE;
        }
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.sendMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.include_item_published_grida, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            if (path.equals("paizhao")) {
                holder.image.setImageResource(R.drawable.icon_addpic_unfocused);
                holder.image.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPhoto();
                    }
                });
            } else {
                Glide.with(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this)
                        .load(path)
                        .placeholder(R.drawable.default_error)
                        .error(R.drawable.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(holder.image);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }
    }

    private void showPhoto() {
        builder = new PhotosDialog.Builder(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
        dialog = builder.create();
        View view = inflater.inflate(R.layout.dialog_photo, null);

        view.findViewById(R.id.image_take).setOnClickListener(this);
        view.findViewById(R.id.image_video).setOnClickListener(this);

        // 相册
        view.findViewById(R.id.image_video).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                PhotoPickerIntent intent = new PhotoPickerIntent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(9); // 最多选择照片数量，默认为6
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE);
//				Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
//				getImage.addCategory(Intent.CATEGORY_OPENABLE);
//				getImage.setType("image/*");
//				startActivityForResult(getImage, PHOTO_REQUEST_GALLERY);
            }
        });

        // 拍照
        view.findViewById(R.id.image_take).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
//				CameraActivity.lanuchForPhoto(DynamicPublishActivity.this);
                Intent intent = new Intent(com.primaryedu.ui.app.growstep.DynamicPublishActivity.this, CameraActivity.class);
                startActivityForResult(intent, REQUEST_PHOTO);
//				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//				// 判断存储卡是否可以用，可用进行存储
//				if (hasSdcard()) {
//					intent.putExtra(MediaStore.EXTRA_OUTPUT,
//							Uri.fromFile(new File(Environment
//									.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
//				}
//
//				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
            }
        });

        dialog.addContentView(view, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();       //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.9
        p.height = (int) (d.getHeight() * 0.5);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    Log.d(TAG, "数量：" + list.size());
                    ispreview = false;
                    loadAdpater(list, ispreview);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    ispreview = true;
                    ArrayList<String> ListExtra = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    loadAdpater(ListExtra, ispreview);
                    break;
//				case CLASSANDGRADE:
//					className = data.getStringExtra("className");
//					classid = data.getStringExtra("calssId");
//					Log.i(TAG, "getParams:className== "+ className);
//					Log.i(TAG, "getParams:classid== "+ classid);
//					tv_classname.setText(className);
//					break;
            }
        }
        if (requestCode == REQUEST_PHOTO) {
            if (resultCode == 1) {
                try {
                    String picture = data.getStringExtra("picture");
//			ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    ArrayList<String> list = new ArrayList<>();
                    Log.d(TAG, "数量：" + list.size());
                    list.add(picture);
                    ispreview = false;
                    loadAdpater(list, ispreview);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    video = data.getStringExtra("video");
                    imagePaths.clear();
                    list_dynamicphoto.clear();
                    Log.i(TAG, "onActivityResult: video======" + video);
                    gridView.setVisibility(View.GONE);
                    videoCover.setVisibility(View.VISIBLE);
                    iv_video_play.setVisibility(View.VISIBLE);
//					mVideo.setVideoPath(video);
                    videoCover.setOnClickListener(this);
//					mVideo.start();
                    showLoading("加载中...");
                    uploadvideo(video);
//			playVideo(video);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public void playVideo(String path) {
//     String path =Environment.getExternalStorageDirectory().getPath() + File.separator +"test.mp4";
//		mVideo.setVideoURI(Uri.parse(path));

        MediaController mctrl = new MediaController(this);
//		mVideo.setMediaController(mctrl);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//		mVideo.setLayoutParams(layoutParams);
//		mVideo.start();
//		mVideo.requestFocus();
    }


    /**
     * 文件上传
     *
     * @param
     */
    public void toUploadFile(String imagespath) {
        String fileKey = "pic";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

//		Map<String, String> params = new HashMap<String, String>();
//		params.put("userid",GlobalData.accountBean.getId());
        String requestURL = Contants.course_api + "/rest/upload/image";
        uploadUtil.uploadFile(imagespath, fileKey,
                requestURL, null);
//		File file = new File(Environment.getExternalStorageDirectory(), picpath1);
//		File file2 = new File(Environment.getExternalStorageDirectory(), picpath2);
//		if (!file.exists()||!file2.exists())
//		{
//			Toast.makeText(DynamicPublishActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
//			return;
//		}
//		Map<String, String> params = new HashMap<>();
//		        params.put("moduleName", "dynamic");
//		        params.put("pics", picpath1);
//
//		String url = "http://47.104.57.2:8080/rest/upload/multiImage";
//		OkHttpUtils.post()//
//				.addFile("mFile", picpath1, file)//
//				.addFile("mFile", picpath2, file2)//
//				.url(url)
//				.params(params)//
//				.build()//
//				.execute(new StringCallback() {
//					@Override
//					public void onError(Call call, Exception e, int id) {
//
//					}
//
//					@Override
//					public void onResponse(String response, int id) {
//						Log.i(TAG, "onResponse: " + response);
//					}
//				});
//
    }

}
